<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    ul,li {list-style: none}
    ul {
      padding: 20px;
      border: 1px solid red;
      cursor: pointer;
    }
    li {
      padding: 0 40px;
      height: 40px;
      line-height: 40px;
      border: 1px solid green;
      text-align: center;
      margin-bottom: 10px;
    }
    span {
      background: lightblue;
      color: red;
      display: inline-block;
      height: 30px;
      line-height: 30px;
      padding: 0 40px;
    }
  </style>
</head>
<body>
<ul class="ul">
  <li>
    <span class="span text">第1个span标签</span>
  </li>
  <li>
    <span class="span">第2个span标签</span>
  </li>
  <li>
    <span class="span">第3个span标签</span>
  </li>
</ul>
<script>
  const ul = document.querySelector('.ul')
  const lis = ul.querySelectorAll('li')
  const spans = ul.querySelectorAll('span')

  // 给ul添加一个on方法
  // type 事件类型
  // selector 元素节点选择器 仅支持标签名 id class三种
  // callback 回调处理方法
  // data 传入的数据 任意类型
  ul.on = function(type, selector, callback, data){
    ul.addEventListener(type, function(e){
      let target = e.target

      // console.log(target.tagName)
      // console.log(target.getAttribute('class'))
      // console.log(target.getAttribute('id'))

      // 按标签名匹配
      if (target.tagName.toLowerCase() === selector) {
        return callback(e, data)
      }

      // 按id名匹配
      if (target.getAttribute('id') === selector) {
        return callback(e, data)
      }

      // 按class名匹配
      let classStr = target.getAttribute('class')
      if (classStr && classStr.split(' ').indexOf(selector.slice(1)) !== -1) {
        return callback(e, data)
      }

    })
  }

  // 使用实例
  ul.on('click', 'li', function(e, data){
    console.log(data)
  }, 'hello')

  ul.on('click', 'span', function(e, data){
    console.log(data)
  }, 'hello span')

  ul.on('click', '.text', function(e, data){
    console.log(data)
  }, 'hello text span')
</script>
</body>
</html>
